
package isv

import (
    "dhfshop/models"
	"strings"
	"errors"
	"time"
	"dhfshop/models/consts"
	"github.com/astaxie/beego/orm"
)

// 用户发布小程序的版本信息和历史信息
type UserApp struct {
	UserAppId       int64     `orm:"column(user_app_id);pk;auto" json:"user_app_id" form:"user_app_id"` //自增主键
    PartnerId       int64       `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`    // 分销商ID
	AppId           string    `orm:"column(app_id);size(32)" json:"app_id" form:"app_id"`                      //上传,审核,发布都需要保存
	Types           string    `orm:"column(types);size(24)" json:"types" form:"types"`                //大黄蜂商城=dhfshop,待扩展
	TemplateId      int64     `orm:"column(template_id);index" json:"template_id" form:"template_id"` //小程序模板id
	Version         string    `orm:"column(version);size(24)" json:"version" form:"version"`          //版本字符串
	Description     string    `orm:"column(description);type(text)" json:"description" form:"description"` //描述
	IsUploaded      int       `orm:"column(is_uploaded);default(0)" json:"is_uploaded" form:"is_uploaded"` //是否已上传，1否，2是  
	UploadTime      time.Time `orm:"column(upload_time);type(datetime);null" json:"-" form:"-"`          //上传时间
	IsSubaduited    int       `orm:"column(is_subaduited);default(0)" json:"is_subaduited" form:"is_subaduited"`//是否已提交审核，1否，2是
	SubaduitId      string    `orm:"column(subaduit_id);size(24)" json:"subaduit_id" form:"subaduit_id"`   //审核ID
	SubaduitTime    time.Time `orm:"column(subaduit_time);type(datetime);null" json:"-" form:"-"`         //提交审核时间
	IsPassed        int       `orm:"column(is_passed);default(0)" json:"is_passed" form:"is_passed"`     //是否审核通过，1否，2是
	IsPublished     int       `orm:"column(is_published);default(0)" json:"is_published" form:"is_published"`  //是否已发布，1否，2是
	PublishTime     time.Time `orm:"column(publish_time);type(datetime);null" json:"-" form:"-"`  //发布时间
	IsVisible       int       `orm:"column(is_visible);default(0)" json:"is_visible" form:"is_visible"` //是否显示，1否，2是
	VisibleTime     time.Time `orm:"column(visible_time);type(datetime);null" json:"-" form:"-"`  //展示时间
	IsDefault       int       `orm:"column(is_default);default(0)" json:"is_default" form:"is_default"` //是是否当前展示版本，1否，2是
	// 非数据库字段
	UploadTimeStr   string    `orm:"-" json:"upload_time" form:"upload_time"`                    
	SubaduitTimeStr string    `orm:"-" json:"subaduit_time" form:"subaduit_time"`                    
	PublishTimeStr  string    `orm:"-" json:"publish_time" form:"publish_time"` 
    VisibleTimeStr  string    `orm:"-" json:"visible_time" form:"visible_time"`                    	
}

func init() {
    orm.RegisterModel(new(UserApp))   
}

func AddUserApp(m *UserApp) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetUserAppId(id int64) (v *UserApp, err error) {
	o := models.GetDefaultDB()
	v = &UserApp{UserAppId: id}
	if err = o.Read(v); err == nil {
		v.UploadTimeStr = v.UploadTime.Format(consts.DATETIME_FORMAT)
		v.SubaduitTimeStr = v.SubaduitTime.Format(consts.DATETIME_FORMAT)
		v.PublishTimeStr = v.PublishTime.Format(consts.DATETIME_FORMAT)
		v.VisibleTimeStr = v.VisibleTime.Format(consts.DATETIME_FORMAT)   
		return v, nil
	}
	return nil, err
}

func GetAllUserApps(query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*UserApp, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(UserApp))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*UserApp
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, userApp := range lists {
			userApp.UploadTimeStr = userApp.UploadTime.Format(consts.DATETIME_FORMAT)
			userApp.SubaduitTimeStr = userApp.SubaduitTime.Format(consts.DATETIME_FORMAT)
			userApp.PublishTimeStr = userApp.PublishTime.Format(consts.DATETIME_FORMAT)
			userApp.VisibleTimeStr = userApp.VisibleTime.Format(consts.DATETIME_FORMAT)   
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateUserAppById(m *UserApp, k ...string) (id int64, err error) {
	o := models.GetDefaultDB()
	v := UserApp{UserAppId: m.UserAppId}
	if err = o.Read(&v); err == nil {
		if id, err = o.Update(m, k...); err != nil {
		   return
		}
	}
	return
}

func DeleteUserAppById(id int64) (err error) {
	o := models.GetDefaultDB()
	v := UserApp{UserAppId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}


